import pandas as pd
from google_trans_new import google_translator
from tqdm import tqdm
import time
import pickle

data = pd.read_csv('case分析抢劫_content.csv', sep=',', encoding='utf-8')
order_id = data['order_id'].values
severity = data['severity'].values
case_type_category2 = data['case_type_category2'].values
content = data['im'].values
trans_im = []  # 存储翻译结果
t = google_translator(timeout=10)
trans_im = []
limit = 30  # 谷歌翻译接口设置访问次数，设置重试次数防止翻译断开
for item in tqdm(content):
    times = 0
    while times < limit:  # 在重试次数范围内不断访问翻译接口
        times += 1
        try:
            dd, pp = item.split('\n')
            translate_dd = t.translate(dd, lang_tgt='zh-cn', lang_src='pt')  # 翻译接口设置源语言和目标语言
            translate_pp = t.translate(pp, lang_tgt='zh-cn', lang_src='pt')
            trans = 'driver: ' + translate_dd + '\n' + 'passenger: ' + translate_pp
            trans_im.append(trans)
            break
        except Exception as e:
            print(e)
# 将源数据和翻译结果写入新表
trans_answer = pd.DataFrame(columns=['order_id', 'severity', 'case_type_category2', 'ori_im', 'trans_im'])
trans_answer['order_id'] = order_id
trans_answer['severity'] = severity
trans_answer['case_type_category2'] = case_type_category2
trans_answer['trans_im'] = trans_im
trans_answer['ori_im'] = content
writer = pd.ExcelWriter('tanslate_抢劫.xlsx')
trans_answer.to_excel(writer, index=False)
writer.save()


# from google_trans_new import google_translator

# translator = google_translator()
# translate_text = translator.translate('我爱你',  lang_src='zh-cn',lang_tgt='en')
# print(translate_text)
